package com.bestcem.xm.common.core.sign.grpc.interceptor;

import com.bestcem.xm.common.core.sign.grpc.core.GrpcTemplate;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import io.grpc.*;

public class GrpcInterceptor implements ServerInterceptor {
    public static final Metadata.Key<String> META_KEY_AUTHORIZATION = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER);

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                                                                 ServerCallHandler<ReqT, RespT> next) {
        String ip = GRpcUtil.getRemoteIp(call, headers);
        String method = call.getMethodDescriptor().getFullMethodName();
        String authorization = headers.get(GrpcInterceptor.META_KEY_AUTHORIZATION);

        Context context = Context.current().withValue(GrpcTemplate.CONTEXT_KEY_IP, ip)
                .withValue(GrpcTemplate.CONTEXT_KEY_METHOD, method)
                .withValue(GrpcTemplate.CONTEXT_KEY_AUTHORIZATION, authorization);
        ServerCall.Listener<ReqT> listener = Contexts.interceptCall(context, call, headers, next);
        return new GrpcListener<>(listener, call, headers);
    }

}
